"user client";
import { searchHosts, update, updateRule } from "../../../api/masterController";

import type {
  ActionType,
  ProColumns,
  ProDescriptionsItemProps,
  RequestData,
} from "@ant-design/pro-components";
import {
  PageContainer,
  ProDescriptions,
  ProTable,
} from "@ant-design/pro-components";
import {Button, Card, Drawer, message, Progress, Tabs, Tag, Typography} from "antd";
import React, { useRef, useState } from "react";
import { FormValueType } from "./Mrshost/UpdateForm";

import CreateModel from "./Mrshost/CreateModel";
import { ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import useStyles from '../style.style';
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading("Configuring");
  try {
    await updateRule({
      name: fields.name,
      desc: fields.desc,
      key: fields.key,
    });
    hide();
    message.success("Configuration is successful");
    return true;
  } catch (error) {
    hide();
    message.error("Configuration failed, please try again!");
    return false;
  }
};

const OfflineData: React.FC = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [modalContent, setModalContent] = useState("");
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] =
      useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailContent, setDetailContent] = useState<string[][]>([]);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.MrsHosts>();
  const [selectedRowsState, setSelectedRows] = useState<API.MrsHosts[]>([]);

  const handleCell = (length: number) => ({
    style: {
      overflow: "hidden",
      maxWidth: length,
      textOverflow: "ellipsis",
      whiteSpace: "nowrap",
    },
    onClick: (e: React.MouseEvent<HTMLDivElement>) => {
      const target = e.currentTarget;
      if (target.style.whiteSpace === "normal") {
        target.style.whiteSpace = "nowrap";
      } else {
        target.style.whiteSpace = "normal";
      }
    },
  });

  const columns: ProColumns<API.MrsHosts>[] = [
    {
      title: "管理IP",
      dataIndex: "ip",
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: "业务IP",
      dataIndex: "businessIp",
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: "主机名",
      dataIndex: "hostname",
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: "节点类型",
      dataIndex: "nodeOMSType",
      valueType: "select",
      valueEnum: {
        NON_OMS: { text: "NON_OMS", status: "Default" },
        ACTIVE_OMS: {
          text: "ACTIVE_OMS",
          status: "Processing",
        },
        STANDBY_OMS: {
          text: "STANDBY_OMS",
          status: "Success",
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: "非管理员 不开放设置",
          },
        ],
      },
    },
    {
      title: "状态",
      dataIndex: "runningStatus",
      valueType: "select",
      valueEnum: {
        BAD: { text: "故障", status: "Error" },
        GOOD: {
          text: "良好",
          status: "Success",
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: "非管理员 不开放设置",
          },
        ],
      },
    },
    {
      title: "CPU核数",
      dataIndex: "cpuCores",
      valueType: "text",
      hideInForm: true,
    },
    {
      title: "CPU使用率",
      dataIndex: "cpuUsage",
      valueType: "text",
      hideInForm: true,
      render: (text, record) => (
          <Progress
              percent={parseInt(record.cpuUsage)}
              status="active"
              strokeColor="#5E7CE0"
          />
      ),
    },
    {
      title: "内存使用率",
      dataIndex: "memoryUsage",
      valueType: "text",
      hideInForm: true,
      render: (text, record) => {
        const totalMemory = parseInt(record.totalMemory);
        const availableMemory = parseInt(record.availableMemory);
        if (totalMemory > 0) {
          const usagePercent = Math.floor(
              ((totalMemory - availableMemory) / totalMemory) * 100,
          );
          return (
              <Progress
                  percent={usagePercent}
                  status="active"
                  strokeColor="#5E7CE0"
              />
          );
        }
        return <Progress percent={0} />;
      },
    },
    {
      title: "可用磁盘空间",
      dataIndex: "availableHardDiskSpace",
      valueType: "text",
      hideInForm: true,
    },
    {
      title: "磁盘空间",
      dataIndex: "totalHardDiskSpace",
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: "实例分布详情",
      dataIndex: "instances",
      width: 180,
      valueType: "option",
      render: (_, record) => {
        const instancesStr = record.instances
            ? record.instances.map((sb) => sb.toString()).join(", ")
            : "";
        return [
          <Button
              type="link"
              key="config"
              onClick={() => {
                const contentArray = instancesStr.split(",");
                const groupedContent: string[][] = [];
                contentArray.forEach((item) => {
                  const startPart = item.split("[")[0];
                  let group = groupedContent.find(
                      (g) => g[0]?.split("[")[0] === startPart,
                  );
                  if (!group) {
                    group = [item];
                    groupedContent.push(group);
                  } else {
                    group.push(item);
                  }
                });
                setDetailContent(groupedContent.filter((g) => g.length > 0));
                setDetailVisible(true);
              }}
          >
            【查看】
          </Button>,
        ];
      },
    },
  ];

  const formattedDetailContent = detailContent.map((group) => {
    /*  if (group[0].startsWith('KrbServer')) {
      return `KrbServer[${group.map(item => item.split('[')[1].split(']')[0]).join(',')}]`;
    } else {

    }*/
    return group.map((item) => item).join(", ");
  });

  /**
   * 标签列表
   * @param tags
   */
  const tagListView = (tags?: string[]) => {
    if (!tags) {
      return <></>;
    }

    return (
        <div style={{ marginBottom: 8 }}>
          {tags.map((tag) => (
              <Tag key={tag}>{tag}</Tag>
          ))}
        </div>
    );
  };
  const { styles } = useStyles();
  return (
      <Card title={<>主机</>} className={styles.offlineCard}>

        <Tabs></Tabs>
        {/*<Typography.Title level={4} style={{marginBottom: 16}}></Typography.Title>*/}

        <ProTable<API.MrsHosts>
            actionRef={actionRef}
            rowKey="ip"
            search={{
              labelWidth: 80,
              searchText: "搜索",
              resetText: "重置",
            }}
            request={async (params, sort, filter): Promise<Partial<RequestData<API.MrsHosts>>> => {
              const response = await searchHosts();
              const data = (response.data || []) as API.MrsHosts[];
              return {
                data,
                success: true,
                total: data.length
              };
            }}
            columns={columns}
            search={false}
            rowSelection={{
              onChange: (_, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }}
        />

        <Drawer
            width="30%"
            visible={detailVisible}
            onClose={() => setDetailVisible(false)}
            closable={false}
            style={{ height: "100%" }}
        >
          <div
              style={{ textAlign: "left", fontWeight: "bold", color: "#5E7CE0" }}
          >
            【查看实例分布详情】
          </div>
          {formattedDetailContent.map((group, index) => (
              <p key={index}>{group}</p>
          ))}
        </Drawer>

        <Drawer
            width={600}
            visible={showDetail}
            onClose={() => {
              setCurrentRow(undefined);
              setShowDetail(false);
            }}
            closable={false}
        >
          {currentRow?.ip && (
              <ProDescriptions<API.MrsHosts>
                  column={2}
                  title={currentRow?.ip}
                  request={async () => ({
                    data: currentRow || {},
                  })}
                  params={{
                    id: currentRow?.ip,
                  }}
                  columns={columns as ProDescriptionsItemProps<API.MrsHosts>[]}
              />
          )}
        </Drawer>

        <CreateModel
            columns={columns}
            onCancel={() => {
              handleModalVisible(false);
            }}
            onSubmit={async (values) => {
              await update(values);
            }}
            visible={createModalVisible}
        />
      </Card>
  );
};
export default OfflineData;
